//
//  HomeController.swift
//  SwiftBase
//
//  Created by 郭艳波 on 2018/3/7.
//  Copyright © 2018年 郭艳波. All rights reserved.
//

import UIKit

class HomeController: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    
    var userList: [User] = []
    
    var currentPage: Int = 1
    
    var header: MJRefreshNormalHeader?
    var footer: MJRefreshAutoNormalFooter?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if self.navigationController != nil {
            self.navigationController!.isNavigationBarHidden = false
        }
        
        self.title = "Home"

        // Do any additional setup after loading the view.
        initTableView()
    }
   
    override func viewWillAppear(_ animated: Bool) {
        if !self.tableView.mj_header.isRefreshing {
            self.tableView.mj_header.beginRefreshing()
        }
        
        self.getUserList()
        
        // 上拉加载
        self.tableView.mj_footer.refreshingBlock = {
            self.currentPage = self.currentPage + 1
            self.getUserList()
        }
        
        // 下拉刷新
        self.tableView.mj_header.refreshingBlock = {
            self.currentPage = 1
            self.userList = []
            self.getUserList()
        }
    }
    
    func getUserList() {
        let user = CoreData.getUser()
        for _ in 0...10 {
            userList.append(user!)
        }
        self.endRefresh()
    }
    
    func endRefresh() {
        DispatchQueue.main.async {
            self.tableView.reloadData()
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
        }
    }
}

extension HomeController: UITableViewDelegate, UITableViewDataSource {
    func initTableView() {
        self.tableView.register(UINib(nibName: "UserViewCell", bundle: nil), forCellReuseIdentifier: "UserViewCell")
        
        self.tableView.backgroundView = nil
        self.tableView.backgroundColor = UIColor.clear
        
        self.tableView.delegate = self
        self.tableView.dataSource = self
        
        self.tableView.separatorStyle = .none
        
        self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 0.01))
        self.tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 0.01))
        self.tableView.allowsSelection = true
        
        header = MJRefreshNormalHeader.init()
        header?.lastUpdatedTimeLabel.isHidden = true
        header?.stateLabel.isHidden = true
        self.tableView.mj_header = header
        
        footer = MJRefreshAutoNormalFooter.init()
        footer?.isRefreshingTitleHidden = true
        footer?.stateLabel.isHidden = true
        self.tableView.mj_footer = footer
        
        if #available(iOS 11.0, *) {
            self.tableView.contentInsetAdjustmentBehavior = .never
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return userList.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let row = indexPath.row
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserViewCell", for: indexPath) as! UserViewCell
        let user = userList[row]
        
        // 获取选中的账号
        let userInStorage = CoreData.getUser()
        
        if (user.id == userInStorage?.id) {
            cell.setData(user: user, selected: true)
        } else {
            cell.setData(user: user, selected: false)
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let row = indexPath.row
        print("\(row)")
    }
}
